<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\ActivityRules;
use App\Models\Admin\Step;

use App\Models\Steps;
use App\Models\Admin\StepReward;
use App\Models\IntegralLog;
use App\Service\HttpService;
use App\Service\MiniProgramService;
use App\Service\StepRewardService;
use App\Service\StepService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WeChatController extends Controller
{

    CONST WEEK_PAGE = 7;
    CONST MONTH_PAGE =10;
    /**
     *  获取微信步数
     * @param MiniProgramService $miniProgramService
     * @param StepService $stepService
     * @param HttpService $httpService
     * @param Step $step
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserStep(MiniProgramService $miniProgramService,StepService $stepService ,HttpService $httpService,Step $step){

        $mobile = request('mobile')??'';
        if(!checkMobile($mobile)){
            return tips(-1,'error','手机号码格式错误');
        }
        // 判断是否是会员
        $url = config('app.url').'member_check?mobile='.$mobile;
        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }
        if($res['status'] == -1){
            return tips(-1,'error','未注册会员');
        }

        // 通过加密的数据
        $session_key = request('session_key')??'';
        $iv = request('iv')??'';
        $encryptedData = request('encryptedData')??'';
        if (!$iv || !$encryptedData || !$session_key) {
            return tips(-1,'error', '错误参数');
        }

        try {
            $errCode = $miniProgramService->decryptData($session_key,$encryptedData, $iv,  $decryptData);
        } catch (\Exception $e) {
            return tips(-1,'error',$e->getMessage());
        }
        Log::debug('stepInfo:-----'.$decryptData);

        $decryptData = json_decode($decryptData,true);

        if ($errCode == 0) {
            DB::beginTransaction();
            try {
                foreach ($decryptData['stepInfoList'] as $key=>$value){
                    $stepList = $step->getStepInfo(['mobile'=>$mobile,'date'=>date('Y-m-d',$value['timestamp'])]);
                    $params = [];
                    if (!$stepList) {
                        $params['mobile'] = $mobile;
                        $params['step'] = $value['step'];
                        $params['date'] = date('Y-m-d',$value['timestamp']);
                        $params['timestamp'] = $value['timestamp'];
                        $params['updated_at'] = date('Y-m-d H:i:s',time());
                        $addStep = Steps::insert($params);
                        if (!$addStep) {
                            throw new \Exception('数据库添加时出错');
                        }
                    } else {
                        $paramss['id'] = $stepList->id;
                        $paramss['mobile'] = $mobile;
                        $paramss['step'] = $value['step'];
                        $paramss['timestamp'] = $value['timestamp'];
                        $paramss['date'] = date('Y-m-d',$value['timestamp']);
                        $paramss['updated_at'] = date('Y-m-d H:i:s',time());

                        $addStep = $stepService->update($paramss);
                        if (!$addStep) {
                            throw new \Exception('数据库更新时出错');
                        }
                    }
                }
            } catch (\Exception $e) {
                DB::rollBack();
                return tips(-1,'error',$e->getMessage());
            }
            DB::commit();
            return tips(1,'success',$decryptData);
        }else{
            return tips(-1,'error',$errCode);
        }
    }

    /**
     * 会员步数页面
     * @param HttpService $httpService
     * @param Step $step
     * @param StepReward $stepReward
     * @return \Illuminate\Http\JsonResponse
     */
    public function step(HttpService $httpService,Step $step,StepReward $stepReward,ActivityRules $activityRules){
        $mobile = request('mobile')??'';

        if(!checkMobile($mobile)){
            return tips(-1,'error','手机号码格式错误');
        }
        // 判断是否是会员
        $url = config('app.url').'member_check?mobile='.$mobile;
        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }
        if($res['status'] == -1){
            return tips(-1,'error','未注册会员');
        }

        $type = request('type')??1;
        $page = request('page')??1;

        $skip = 0;
        $take = 0;
        if ($type ==1) {
            $take = self::WEEK_PAGE;
            $time = [date('Y-m-d 00:00:00', strtotime('this week monday')),date('Y-m-d 23:59:59', strtotime('this week sunday'))];
        }elseif ($type == 2){
            $take = self::MONTH_PAGE;
            $time = [date('Y-m-01 00:00:00'),date('Y-m-d 23:59:59', strtotime('Last day of this month'))];
            if($page > 1){
                $skip = self::MONTH_PAGE * $page - self::MONTH_PAGE;
            }
        }
        $stepCount = 0;
        $list = $step->getAllStep($skip,$take,['mobile'=>$mobile],$time);

        $count = $step->getStepCount(['mobile'=>$mobile],$time);


        $total_page = ceil($count / $take);    // 总页数

        if(count($list) > 0){
            foreach ($list as $key=>$value){
                $stepCount += $value->step;
                $list[$key]->date = date('Y-m-d', strtotime($value->date));
            }
        }

        $day = date('m' ,time());
        $stepReward = $stepReward->getStepInfo(['month'=>$day]);
        if($stepReward){
            $month = $stepReward->month;
            $content = $stepReward->content;
        }
        $is_condition = 1;
        $active_id = request('active_id',2);
        $activityInfo = $activityRules->where('id',$active_id)->first();
        $times = [date('Y-m-01 00:00:00'),date('Y-m-d 23:59:59', strtotime('Last day of this month'))];
        $num = $step->where('mobile',$mobile)->whereBetween('date',$times)->sum('step');
        // 判断是否够步数
        if ($num >= $activityInfo['condition']) {

            $is_condition = 2;
        }
        return tips(1,'success',[
            'step_count' => $stepCount,
            'month' => $month??$day,
            'content' => $content??'',
            'is_condition' => $is_condition,
            'activityInfo' => $activityInfo,
            'current_page' => $page,    // 当前页
            'total_page' => $total_page,// 总页数
            'total' => $count,           // 总条数
            'per_page' => $take,     // 页显示条数
            'list' => $list
        ]);
    }

    /**
     *
     * @author Bryant
     * @date 2020-10-15 16:10
     *
     * 步数打卡获取积分
     */
    public function getIntegral(HttpService $httpService,ActivityRules $activityRules,IntegralLog $integralLog)
    {
        $mobile = request('mobile');
        $active_id = request('active_id',2);

        if (!checkMobile($mobile)) {
            return tips(-1, 'error', '手机号码格式不正确');
        }

        // 判断是否是会员
        $isUser = $this->isUser($httpService,$mobile);
        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }

        $activityInfo = $activityRules->where('id',$active_id)->first();

        if ($activityInfo['status'] != 1) {

            return tips(-1,'error','该活动已结束');
        }
        $start_time = strtotime($activityInfo['start_time']);

        $end_time = strtotime($activityInfo['end_time']);

        if (time() <$start_time || time() > $end_time) {

            return tips(-1,'error','不在活动期');
        }
        // 本月开始时间和结束时间
        $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
        $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));

        $stepNum = Step::where('mobile',$mobile)->whereBetween('timestamp',[$beginThismonth,$endThismonth])->sum('step');

        if ($stepNum < $activityInfo['condition']) {

            return tips(-1,'error','您的累计步数不足,暂时无法兑换积分');
        }

        // 判断本月是否兑换过

        $is_get = $integralLog->where('mobile',$mobile)->where('from_type',2)->whereBetween('created_at',[$beginThismonth,$endThismonth])->count('id');

        if ($is_get >= 1) {

            return tips(-1,'error','本月您已经领取过了');
        }



        //获取用户的会员号
        $str = request(['queryStr']);

        $userInfo = $this -> getMemberCard($httpService,$str);

        if ($userInfo['Statu'] !=1) {

            return tips('-1','error',$userInfo['Msg']);
        }

        $userCard = $userInfo['VCardNO'];

        if (!$userCard) {
            return tips(-1,'error','您暂时没有领用会员卡，请前往周黑鸭公众号领用会员卡');
        }


        $nums = rand(100000,999999);
        // 操作积分
        DB::beginTransaction();

        try {
            // 获取CRM 的数据
            $getUrl = "http://127.0.0.1:8898"; //C# 中间件的访问地址
            $param = [
                'action' => 'ZRFC_INTERACTIONPOINTS_PAY', //访问的方法
                'ZZCHANNEL' => "HNX", // 渠道
                'PARTNER_ID' =>$userCard, // 会员号
                'MOB_NUMBER' =>"",
                'ZZAUART' => 'S02',
                'ZZVBELN' => date('YmdHis',time()).$nums,
                'ZZCPSYDAT' => date('YmdHis',time()),
                'ZEPOINT_ADD' => $activityInfo['point'],
                'ZEPOINT_RED' => '',
                'ZEPRODUCTS_ID' => 'HDJF',
                'ZZCPSTORE' => "SZ09997",

            ];
            $param = json_encode($param,true);

            $res = $this->curl_open($getUrl,$param);

            if ($res['errcode'] == 4002) {

                $res = $this->curl_open($getUrl,$param);
            }

            if($res['rtval']['E_RETURN']['MSTYP'] != 'S'){

                return tips(-1,'error',$res['rtval']['E_RETURN']['MSMEG']);
            }

            $data = [

                'integral' => $activityInfo['point'],
                'from_type' => 1, // 门店打卡
                'type' => 1, //收入
                'mobile' => $mobile,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
            // 加入记录表
            $result = $integralLog->insert($data);

            if (!$result) {

                throw new \Exception('添加数据有问题');
            }
        } catch (\Exception $e) {

            DB::rollBack();
            return tips(-1,'error',$e->getMessage());
        }
        DB::commit();

        return tips(1,'success','兑换成功');

    }
}
